﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using XStudio.XCRF.Data;
using XStudio.XCRF.Data.Business;
using XStudio.XCRF.Data.Business.Permissions;
using XStudio.XCRF.Data.Entities;
using XStudio.XCRF.Data.Entities.BasicInfo;
using XStudio.XCRF.Data.Entities.CureInfo;
using XStudio.XCRF.Data.Entities.LabCheck;
using XStudio.XCRF.Web.Export;

namespace XStudio.XCRF.Web.Controllers
{
    /// <summary>
    /// 病例报告表控制器
    /// </summary>
    public partial class CRFController : BaseController
    {
        #region 病例报告
        /// <summary>
        /// 处理添加病历报告表的页面请求
        /// </summary>
        /// <param name="patientID">患者ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFAdd(Guid patientID)
        {
            Patient patient = DataContext.Patients.Find(patientID);
            CRF crf = new CRF
            {
                
                PatientID = patientID,
                Patient = patient,
                ResearcherID = DataContext.CurrentMember.ID,
                Researcher = DataContext.CurrentMember,
                HospitalID = DataContext.CurrentMember.HospitalID,
                Hospital = DataContext.CurrentMember.Hospital,
                HospitalCode = DataContext.CurrentMember.Hospital.Code
            };
            return View(crf);
        }

        /// <summary>
        /// 处理添加病例报告表的POST请求
        /// </summary>
        /// <param name="crf">欲添加的病历报告表</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        [HttpPost]
        public JsonResult CRFAdd(CRF crf)
        {

            if ((crf.Patient.Name != null) && (crf.Patient.IDCard != null) && (crf.Patient.Phone != null))
            {
                try
                {
                    String crfCode = DataContext.CRFs.Where(c => c.HospitalID == crf.HospitalID).Max(c => c.CrfCode);
                    int code = Convert.ToInt32("1" + crfCode);
                    code++;
                    crfCode = code.ToString().Substring(1 , code.ToString().Length - 1);
                    crf.CrfCode = crfCode;
                    Patient patient = DataContext.Patients
                        .Find(p => p.IDCard == crf.Patient.IDCard).FirstOrDefault();
                    if (patient != null)
                    {
                        patient.Name = crf.Patient.Name;
                        patient.Gender = crf.Patient.Gender;
                        patient.TreatDepart = crf.Patient.TreatDepart;
                        patient.Nationality = crf.Patient.Nationality;
                        patient.Birthday = crf.Patient.Birthday;
                        patient.Phone = crf.Patient.Phone;
                        patient.Job = crf.Patient.Job;
                        patient.JobKind = crf.Patient.JobKind;
                        patient.Address = crf.Patient.Address;
                        patient.SocialID = crf.Patient.SocialID;
                        crf.Patient = null;
                        crf.PatientID = patient.ID;
                    }
                    DataContext.CRFs.Add(crf);
                    DataContext.SaveChanges();
                    //return Json(crf);
                    return Json(new { ID = crf.ID });
                }
                catch
                {
                    return Json(null);
                }
            }
            else
            {
                return Json(null);
            }
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFAddSelf()
        {
            CRF crf = new CRF
            {
                Patient = new Patient(),
                ResearcherID = DataContext.CurrentMember.ID,
                Researcher = DataContext.CurrentMember,
                HospitalID = DataContext.CurrentMember.HospitalID,
                Hospital = DataContext.CurrentMember.Hospital,
                HospitalCode = DataContext.CurrentMember.Hospital.Code,
            };
            return View(crf);
        }

        /// <summary>
        /// 处理编辑病例报告表的页面请求
        /// </summary>
        /// <param name="crfID">病历报告表ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFEdit(Guid crfID)
        {
            CRF crf = DataContext.CRFs
                .Include(c => c.Researcher)
                .Include(c => c.Patient)
                .Include(c => c.Hospital)
                .Find(crfID);
            if (crf.PatientID == null)
                crf.Patient = new Patient();
            return View(crf);
        }

        /// <summary>
        /// 处理病历报告表编辑请求
        /// </summary>
        /// <param name="crf">欲编辑的病历报告报告表</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        [HttpPost]
        public JsonResult CRFEdit(CRF crf)
        {
            try
            {
                CRF oldCRF = DataContext.CRFs.Find(crf.ID);
                oldCRF.StartTime = crf.StartTime;
                oldCRF.HospitalCode = crf.HospitalCode;
                oldCRF.CrfCode = crf.CrfCode;
                oldCRF.Patient.Name = crf.Patient.Name;
                oldCRF.Patient.Gender = crf.Patient.Gender;
                oldCRF.Patient.TreatDepart = crf.Patient.TreatDepart;
                oldCRF.Patient.Birthday = crf.Patient.Birthday;
                oldCRF.Patient.Phone = crf.Patient.Phone;
                oldCRF.Patient.Job = crf.Patient.Job;
                oldCRF.Patient.JobKind = crf.Patient.JobKind;
                oldCRF.Patient.Address = crf.Patient.Address;
                oldCRF.Patient.BirthPlace = crf.Patient.BirthPlace;
                oldCRF.Patient.Marriage = crf.Patient.Marriage;
                DataContext.SaveChanges();
                return Json(new { ID = crf.ID });
            }
            catch
            {
                return Json(null);
            }
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFDetail(Guid crfID)
        {
            CRF crf = DataContext.CRFs
                .Include(c => c.Researcher)
                .Include(c => c.Patient)
                .Include(c => c.Hospital)
                .Find(crfID);
            return View(crf);
        }


        [HttpPost]
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFDelete(Guid crfID)
        {
            try
            {
                CRF crf = ((IQueryable<CRF>)DataContext.CRFs).Find(crfID);
                DataContext.CRFs.Remove(crf);
                DataContext.SaveChanges();
                return Json(new { ID = crfID });
            }
            catch
            {
                return Json(null);
            }

        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult _CRFDelete(CRF crf)
        {
            CRF crf_db = ((IQueryable<CRF>)DataContext.CRFs)
                .Find(crf.ID);
            DataContext.CRFs.Remove(crf_db);
            DataContext.SaveChanges();
            return _CRFList((Guid)HospitalID);
        }
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFList(Guid hospitalID)
        {
            ViewBag.HospitalCode = Request.Form["HospitalCode"];
            ViewBag.CrfCode = Request.Form["CrfCode"];
            ViewBag.ResearcherName = Request.Form["ResearcherName"];
            ViewBag.StartTime = Request.Form["StartTime"];
            Hospital hospital = ((IQueryable<Hospital>)DataContext.Hospitals).Find(hospitalID);
            return View(hospital);
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        public ActionResult _CRFList(Guid hospitalID)
        {
            IQueryable<CRF> crfs = DataContext.CRFs
                .Include(crf => crf.Researcher).Include(crf=>crf.Patient)
               .Find(crf => crf.HospitalID == hospitalID);
            int count = crfs.Count();
            crfs = crfs.OrderBy(crf => crf.LastModifyTime);
            List<CRF> dtos = new List<CRF>();
            foreach (CRF crf in crfs)
            {
                CRF dto = new CRF();
                dto.ID = crf.ID;
                dto.HospitalCode = crf.HospitalCode;
                dto.CrfCode = crf.CrfCode;
                dto.ResearcherID = crf.ResearcherID;
                dto.Researcher = new Member { RealName = crf.Researcher.RealName };
                Patient p = new Patient (){
                    Name = crf.Patient.Name
                };
                dto.Patient = p;
                dto.StartTime = crf.StartTime;
                dtos.Add(dto);
            }
            return Json(new GridModel<CRF>
            {
                Data = dtos,
                Total = count
            });
        }
        #endregion 病例报告

        #region 基本信息
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult BasicInfoDetail(Guid crfID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes
                .Include(b => b.CRF)
                .Include(b => b.CRF.Patient)
                .Include(b => b.FamilyHistories)
                .Include(b => b.AllergyHistories)
                .Include(b => b.Chemos)
                .Include(b => b.Radios)
                .Include(b => b.OtherCures)
                .Include(b => b.OtherMerges)
                .Include(b => b.LastModifier)
                .Include(b => b.Creater)
                .Find(b => b.CRFID == crfID).FirstOrDefault();
            if (basicInfo != null)
                return PartialView(basicInfo);
            else
                return PartialView("BasicInfoNull", new BasicInfo { CRFID = crfID });
        }
        #endregion 基本信息

        #region 实验室信息
        [GridAction]
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult LabCheckGridList(Guid crfID)
        {
            List<LabCheck> labChecks = DataContext.LabChecks
                .Include(l => l.Creater)
                .Include(l => l.LastModifier)
                .Find(l => l.CRFID == crfID).ToList()
                .Select(labcheck =>
                new LabCheck
                {
                    ID = labcheck.ID,
                    Time = labcheck.Time,
                    LastModifyTime = labcheck.LastModifyTime,
                    LastModifier = new Member { RealName = labcheck.LastModifier.RealName },
                    CreateTime = labcheck.CreateTime,
                    Creater = new Member { RealName = labcheck.Creater.RealName }
                }).ToList();
            //return Json(new GridModel<LabCheck>(labChecks));
            return View(new GridModel(labChecks));
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult LabCheckDelete(LabCheck labCheck)
        {
            //CureInfo cureInfo = DataContext.CureInfoes.Find(cureInfoID);
            LabCheck labCheck_db = DataContext.LabChecks.Include(l => l.CRF).Find(labCheck.ID);
            labCheck.CRFID = labCheck_db.CRFID;
            DataContext.LabChecks.Remove(labCheck_db);
            DataContext.SaveChanges();
            return LabCheckGridList((Guid)labCheck.CRFID);
            //throw new NotImplementedException();
        }
        #endregion 实验室信息

        #region 治疗信息
        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult CureInfoGridList(Guid crfID)
        {
            List<CureInfo> cureInfoes = DataContext.CureInfoes
                .Include(c => c.Creater)
                .Include(c => c.LastModifier)
                .Find(c => c.CRFID == crfID).ToList()
                .Select(cure => new CureInfo
                {
                    ID = cure.ID,
                    Time = cure.Time,
                    LastModifyTime = cure.LastModifyTime,
                    LastModifier = new Member { RealName = cure.LastModifier.RealName },
                    CreateTime = cure.CreateTime,
                    Creater = new Member { RealName = cure.Creater.RealName }
                }).ToList();
            return View(new GridModel(cureInfoes));
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult CureInfoDelete(CureInfo cureInfo)
        {
            //CureInfo cureInfo = DataContext.CureInfoes.Find(cureInfoID);
            CureInfo cureInfo_db = DataContext.CureInfoes.Include(l => l.CRF).Find(cureInfo.ID);
            cureInfo.CRFID = cureInfo_db.CRFID;
            DataContext.CureInfoes.Remove(cureInfo_db);
            DataContext.SaveChanges();
            return CureInfoGridList((Guid)cureInfo.CRFID);
            //throw new NotImplementedException();
        }
        #endregion 治疗信息

        #region 导出
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult Export(Guid[] checkRecords)
        {
            if (checkRecords == null)
                return RedirectToAction("CRFList", "CRF", new { hospitalID = (Guid)HospitalID });
            ExportHelper h = new ExportHelper();
            XCRFContext ct = new XCRFContext();
            List<CRF> crfs = new List<CRF>();
            for (int i = 0; i < checkRecords.Length; i++)
            {
                CRF crf = ct.CRFs.Include("Researcher").Include("Patient")
                    .Include("Hospital").Find(checkRecords[i]);
                crfs.Add(crf);
            }
            h.exportCRFs(crfs);
            return RedirectToAction("CRFList", "CRF", new { hospitalID = (Guid)HospitalID });
        }
        #endregion









        [DefaultPermission(PermissionType.Allow)]
        public ActionResult CRFListtest(Guid hospitalID,string name)
        {
            Hospital hospital = ((IQueryable<Hospital>)DataContext.Hospitals).Find(hospitalID);
            return View(hospital);
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        public ActionResult _CRFListtest(Guid hospitalID, string name)
        {
            IQueryable<CRF> crfs = DataContext.CRFs
                .Include(crf => crf.Researcher)
                .Include(crf => crf.Patient)
               .Find(crf => crf.HospitalID == hospitalID)
               .Find(crf => crf.Patient.Name == name);
            int count = crfs.Count();
            crfs = crfs.OrderBy(crf => crf.LastModifyTime);
            List<CRF> dtos = new List<CRF>();
            foreach (CRF crf in crfs)
            {
                CRF dto = new CRF();
                dto.ID = crf.ID;
                dto.HospitalCode = crf.HospitalCode;
                dto.CrfCode = crf.CrfCode;
                dto.ResearcherID = crf.ResearcherID;
                dto.Researcher = new Member { RealName = crf.Researcher.RealName };
                dto.StartTime = crf.StartTime;
                dtos.Add(dto);
            }
            return Json(new GridModel<CRF>
            {
                Data = dtos,
                Total = count
            });
        }
    }

}
